import 'package:backend.core/logger/logger.dart';
import 'package:shelf/shelf.dart';

abstract class LogRequests {
  Middleware call();
}

class LogRequestsImpl implements LogRequests {
  const LogRequestsImpl();

  @override
  Middleware call() {
    return (innerHandler) {
      return (request) {
        final query = request.requestedUri.query;
        final method = request.method;
        final url = '${request.requestedUri.path}${query == '' ? '' : '?$query'}';

        return Future.sync(() => innerHandler(request)).then((response) {
          final statusCode = response.statusCode;
          final message = '${method.padRight(4)} [$statusCode] $url';

          Logger().v(message);

          return response;
        }, onError: (Object error, StackTrace stackTrace) {
          if (error is HijackException) {
            throw error;
          }

          final message = '${method.padRight(4)} $url';

          Logger().e(message, error, stackTrace);

          throw error;
        });
      };
    };
  }
}
